import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { AddressSelector } from 'antd-pro-biz';
import { Icon, Input, Card, Select, Tabs, Button, Row, Col, Spin, Modal } from 'antd';
import debounce from 'lodash/debounce';
import api from '@/api';
import { ADDRESS_TYPE, TRANSPORT_TYPE } from '@/Constants';
import styles from './index.less';
import _ from 'lodash';

const { Option } = Select;
const { TabPane } = Tabs;

function callback(key) {
  console.log(key);
}

function callback2(key) {
  console.log(key);
}

// const provinceList = [
//   {
//     "addressType": 2,
//     "groupCode": 0,
//     "level": 2,
//     "code": 110000,
//     "parentCode": 1,
//     "name": "北京市"
//   },
//   {
//     "addressType": 2,
//     "groupCode": 0,
//     "level": 2,
//     "code": 120000,
//     "parentCode": 1,
//     "name": "天津市"
//   },
//   {
//     "addressType": 2,
//     "groupCode": 0,
//     "level": 2,
//     "code": 130000,
//     "parentCode": 1,
//     "name": "河北省"
//   },
//   {
//     "addressType": 2,
//     "groupCode": 0,
//     "level": 2,
//     "code": 140000,
//     "parentCode": 1,
//     "name": "山西省"
//   },
//   {
//     "addressType": 2,
//     "groupCode": 0,
//     "level": 2,
//     "code": 150000,
//     "parentCode": 1,
//     "name": "内蒙古自治区"
//   },
//   {
//     "addressType": 2,
//     "groupCode": 0,
//     "level": 2,
//     "code": 110101305,
//     "parentCode": 1,
//     "name": "山东省"
//   },
//   {
//     "addressType": 2,
//     "groupCode": 0,
//     "level": 2,
//     "code": 110101306,
//     "parentCode": 1,
//     "name": "重庆市"
//   },
//   {
//     "addressType": 2,
//     "groupCode": 0,
//     "level": 2,
//     "code": 110101307,
//     "parentCode": 1,
//     "name": "广东省"
//   },
//   {
//     "addressType": 2,
//     "groupCode": 0,
//     "level": 2,
//     "code": 110101308,
//     "parentCode": 1,
//     "name": "贵州省"
//   },
//   {
//     "addressType": 2,
//     "groupCode": 0,
//     "level": 2,
//     "code": 110101309,
//     "parentCode": 1,
//     "name": "手工添加测试用省"
//   }
// ]

// const cityList = [
//   {
//     "addressType": 2,
//     "groupCode": 0,
//     "level": 3,
//     "code": 110100,
//     "parentCode": 110000,
//     "name": "北京市"
//   }
// ]

// const districtList = [
//   {
//     "addressType": 2,
//     "groupCode": 0,
//     "level": 4,
//     "code": 110101,
//     "parentCode": 110100,
//     "name": "东城区"
//   }
// ]

@connect(({ add }) => ({ add }))

class AddSelect extends Component {
  constructor(props) {
    super(props);
    this.lastFetchId = 0; //+++
    this.fetchUser = debounce(this.fetchUser, 800); //+++
    this.state = {
      showAddModal: 'none',
      inputBlur: false,
      boxBlue: false,
      addressInputValue: '',
      province: '省/直辖市',
      provinceList: [],
      city: '',
      cityList: [],
      district: '',
      districtList: [],
      activeKey: '1',
      selectOptionList: [],
      data: [], // +++
      value: [],  // +++
      fetching: false,  // +++
    };
  }

  // // 模态框展示
  // showModal = () => {
  //   this.setState({
  //     visible: true,
  //   });
  // };

  // // 模态框关闭
  // handleCancel = e => {
  //   console.log(e);
  //   this.setState({
  //     visible: false,
  //   });
  // };

  // 防抖 做搜索的时候用
  fetchUser = value => {
    console.log('fetching user', value);
    this.lastFetchId += 1;
    const fetchId = this.lastFetchId;
    this.setState({ data: [], fetching: true });
    fetch("http://172.27.2.30:8005/ota/addressFacade/findByParam", {
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        "searchContent": value,
      })
    })
      .then(response => response.json())
      .then(body => {
        console.log(body)
        if (fetchId !== this.lastFetchId) {
          // for fetch callback order
          return;
        }
        const data = body.data.list.map(item => ({
          text: item.name,
          value: item.id,
        }));
        this.setState({ data, fetching: false });
      });
  };

  handleChange = () => {
    console.log('111')
  };

  // 输入框聚焦，打开三级联动器
  inputFocus = () => {
    this.showAddModal()
    console.log('inputFocus')
  }

  // 选中选项时 ******
  onChange = (e) => {
    console.log(e)
    this.setState({
      addressInputValue: e
    })
  }

  // 输入内容时，改变输入框的值，隐藏三级联动
  onSearch = (e) => {
    const { dispatch } = this.props
    dispatch({
      type: 'add/addressSearchAsync',
      payload: {
        data: {
          searchContent: e
        }
      }
    }).then(({data}) => {
      this.setState({
        selectOptionList: data.list
      })
      console.log(data.list)
    })

    this.setState({
      addressInputValue: e,
      showAddModal: 'none'
    })
  }
  
  componentDidMount () {
    // 初始化获取所有省份
    const { dispatch } = this.props
    dispatch({
      type: 'add/addressSelectAsync',
      payload: {
        data: {
          groupCode: 0,
          parentCode: 1
        }
      }
    }).then(({data}) => {
      this.setState({
        provinceList: data
      })
    })

    dispatch({
      type: 'add/addressSearchAsync',
      payload: {
        data: {
          searchContent: ''
        }
      }
    }).then(({data}) => {
      this.setState({
        selectOptionList: data.list
      })
    })
  }

  provinceClick = (e, key) => {
    const { dispatch } = this.props
    dispatch({
      type: 'add/addressSelectAsync',
      payload: {
        data: {
          groupCode: 0,
          parentCode: this.state.provinceList[key].code
        }
      }
    }).then(({data}) => {
      this.setState({
        addressInputValue: this.state.provinceList[key].name,
        province: this.state.provinceList[key].name,
        activeKey: '2',
        cityList: data,
        city: '请选择',
        districtList: [],
        district: '',
      })
    })
  }

  cityClick = (e, key) => {
    const { dispatch } = this.props
    dispatch({
      type: 'add/addressSelectAsync',
      payload: {
        data: {
          groupCode: 0,
          parentCode: this.state.cityList[key].code
        }
      }
    }).then(({data}) => {
      this.setState({
        addressInputValue: this.state.province + '-' + this.state.cityList[key].name,
        city: this.state.cityList[key].name,
        activeKey: '3',
        districtList: data,
        district: '请选择'
      })
    })
  }

  districtClick = (e, key) => {
    this.setState({
      addressInputValue: this.state.province + '-' + this.state.city+ '-' + this.state.districtList[key].name,
      district: this.state.districtList[key].name,
      showAddModal: 'none'
    })
    // this.state.addressInputValue = this.state.province + '-' + this.state.city+ '-' + this.state.districtList[key].name
    this.props.onChange(this.state.province + '-' + this.state.city+ '-' + this.state.districtList[key].name)
  }

  tabClick = (key, e) => {
    console.log(key)
    this.setState({
      activeKey: key.toString()
    })
  }
  
  toParent = () => {
    this.props.parent.getAddress(this, this.state.addressInputValue)
  }

  showAddModal = () => {
    this.setState({
      showAddModal: 'block'
    })
  }

  render() {
    const { cities, districts, provinceList, cityList, districtList, selectOptionList, fetching, data, value } = this.state
    return (
      <div style={{position: 'relative', fontSize: '16px'}} id="addressBox">
        <Input
          onClick={this.inputFocus}
          onChange={this.handleChange}value={this.state.addressInputValue}
        />
        {/* <Select
          showArrow={false} //是否显示下拉箭头
          // mode="tags"
          showSearch={true} //单选模式可搜索
          labelInValue
          value={value}
          notFoundContent={fetching ? <Spin size="small" /> : null}
          filterOption={false}
          onSearch={this.fetchUser}
          onChange={this.handleChange}
          style={{ width: '100%' }}
        >
          {data.map(d => (
            <Option key={d.value}>{d.text}</Option>
          ))}
        </Select> */}
        {/* <Modal 
          visible={this.state.visible}
          onCancel={this.handleCancel} 
          style={{display: this.state.showAddModal, top: '300px'}}
          getContainer={this.getContainer}
          closable={false}
          footer={null}
          mask={false}
        > */}
        <Card className={styles.cardBox} style={{display: this.state.showAddModal}}>
          <p style={{fontSize: '12px', color: '#999'}}>温馨提示：支持中文、拼音或首字母，如：西安 或 XA</p>
          {/* 选项卡 */}
          <Tabs defaultActiveKey='1' onChange={callback} className={styles.tabBox}>
            <TabPane tab="中国" key="1">
              {/* -------标签页的做法------- */}
              <Tabs activeKey={this.state.activeKey} onTabClick={(key, e) => this.tabClick(key, e)} onChange={callback2} className={styles.cityBox}>
                <TabPane tab={this.state.province} key="1" className={styles.cityTabBox}>
                  <Row>
                    {provinceList.map((item, key) => {
                      return <Col span={8} className={styles.colBtn}>
                          <Button className={styles.addressBtn} value={item.code} onClick={(e) => this.provinceClick(e, key)}>
                            {item.name}
                          </Button>
                      </Col>
                    })}
                  </Row>
                </TabPane>
                {this.state.city !== '' ? 
                  <TabPane tab={this.state.city} key="2" className={styles.cityTabBox}>
                    <Row>
                      {cityList.map((item, key) => {
                        return <Col span={8} className={styles.colBtn}>
                            <Button className={styles.addressBtn} value={item.code} onClick={(e) => this.cityClick(e, key)}>
                              {item.name}
                            </Button>
                        </Col>
                      })}
                    </Row>
                  </TabPane>
                  :
                  null
                }
                {this.state.district !== '' ?
                  <TabPane tab={this.state.district} key="3" className={styles.cityTabBox}>
                    <Row>
                      {districtList.map((item, key) => {
                        return <Col span={8} className={styles.colBtn}>
                            <Button className={styles.addressBtn} value={item.code} onClick={(e) => this.districtClick(e, key)}>
                              {item.name}
                            </Button>
                        </Col>
                      })}
                    </Row>
                  </TabPane>
                  :
                  null
                }
              </Tabs>
              {/* -------Select的做法------ */}
              {/* <Select
                style={{ width: 120 }}
                onChange={this.onProvinceChange}
              >
                {provinceData.map(province => (
                  <Option key={province}>{province}</Option>
                ))}
              </Select>
              <Select
                style={{ width: 120 }}
                value={this.state.secondCity}
                onChange={this.onCityChange}
              >
                {cities.map(city => (
                  <Option key={city}>{city}</Option>
                ))}
              </Select>
              <Select
                style={{ width: 120 }}
                value={this.state.district}
                onChange={this.onDistrictChange}
              >
                {districts.map(district => (
                  <Option key={district}>{district}</Option>
                ))}
              </Select> */}
            </TabPane>
            <TabPane tab="国际" key="2">
              
            </TabPane>
          </Tabs>
        {/* </Modal> */}
        </Card>
      </div>
    );
  }
}

export default AddSelect;
